package network.websocket;

import config.AppConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;

/**
 * ws服务器
 *
 * @author wyl
 */
public class WSServer {
    public static final WSServer Instance = new WSServer();
    private static final Logger logger = Logger.getLogger(WSServer.class);
    AtomicReference<NioEventLoopGroup> boss = new AtomicReference<>(null);
    AtomicReference<NioEventLoopGroup> work = new AtomicReference<>(null);
    AtomicReference<ServerBootstrap> bootstrap = new AtomicReference<>(null);
    private volatile boolean isRun = false;

    private ChannelFuture init() {
        //读取配置
        int port = AppConfig.ServerConfig.getPort();
        boss.set(new NioEventLoopGroup());
        work.set(new NioEventLoopGroup());
        bootstrap.set(new ServerBootstrap());
        return bootstrap.get().group(boss.get(), work.get())
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                .childHandler(new WSInitializer())
                //加载配置
                .bind(new InetSocketAddress(port));

    }

    public void startServer() {
        if (!isRun) {
            ExecutorService service = Executors.newSingleThreadExecutor();
            service.execute(() -> {
                try {
                    ChannelFuture channelFuture = init();
                    Channel channel = channelFuture.sync().channel();
                    logger.info("服务器启动了" + channel);
                    isRun = true;
                    channel.closeFuture().sync();
                    isRun = false;
                    logger.info("服务器关闭了");
                } catch (Exception exception) {
                    logger.error("服务器异常了", exception);
                } finally {
                    service.shutdown();
                }
            });
        }
    }


    public void restartServer() {
        if (isRun) {
            work.get().shutdownGracefully();
            boss.get().shutdownGracefully();
        }
        startServer();
    }

    public boolean isRun() {
        return isRun;
    }


}
